<template>
  <div class="d-flex-c">
    <div class="flex-between m-b-tiny switch-button-tab-bg flex-0 ">
      <SwitchTab
        is-button
        :tab-list="ybyjTabList"
        v-model="ybyjTab"
      />
      <SwitchTab
        :tab-list="queryTabList"
        v-show="ybyjTab === 'hsyj'"
        v-model="yjQueryType"
        @change="fetchChartData"
      />
      <el-date-picker
        v-show="ybyjTab === 'ybcg'"
        v-model="ybQueryDate"
        class="blue-range-date-picker"
        popper-class="blue-select-dropdown"
        value-format="yyyy-MM-dd HH:mm:ss"
        :clearable="false"
        prefix-icon=""
        size="mini"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="fetchTableData"
      />

      <!-- <SwitchTab
        :tab-list="queryDayList"
        v-show="ybyjTab === 'ybcg'"
        v-model="ybQueryType"
        @change="fetchTableData"
      /> -->
    </div>
    <div
      class="panel-zone-bg flex-1"
    >
      <div
        class="flex-between flex-1 full-width"
        v-show="ybyjTab === 'hsyj'"
        v-loading="chartLoading"
      >
        <div class="flex-1 full-height d-flex-c jc-c">
          <div class="flex-1  overflow-hidden position-relative">
            <BKChart
              :option="pieOptions"
            />
            <div class="absolute-center d-flex-c">
              <div class="m-b-tiny">
                <span class="f-30 ff-agencyyr f-w7 c-text-blue"> {{ pieTotal }}</span>
                <span class="f-16">个</span>
              </div>
              <div class="f-16">
                全省
              </div>
            </div>
          </div>

          <div class="flex-wrap m-t-tiny">
            <div
              v-for="legend in pieChartConfig"
              :key="legend.field"
              class="half-width  pie-legend flex-ai-c jc-c"
            >
              <div
                class="color-rect  "
                :style="{color:legend.color}"
              />
              <span class="f-12 c-white m-r-mini">
                {{ legend.name }}
              </span>
              <span
                class="f-20 ff-agencyyr f-w7 c-pointer"
                :style="{color:legend.color}"
                @click="showReverseCheck(legend.field)"
              >
                {{ pieChartData[legend.field] }}
              </span>
            </div>
          </div>
        </div>
        <div class="d-flex-c flex-1 full-height">
          <div
            class="little-title m-b-tiny"
          >
            各区域统计情况
          </div>
          <div class="flex-1">
            <BKChart
              :option="lineOptions"
            />
          </div>
        </div>
      </div>
      <div
        v-show="ybyjTab === 'ybcg'"
        class="flex-1 overflow-hidden"
      >
        <BKTable
          ref="grid"
          :columns="achievementColumns"
          :data="achievementTableData"
          :loading="tableLoading"
          :has-pager="false"
          border="none"
          :highlight-current-row="true"
          :stripe="false"
          :has-seq="false"
          class="ysqjcdp-table"
          header-cell-class-name="wrap-header-cell"
        />
      </div>
    </div>
    <DetailModal
      v-if="detailVisible"
      :visible="detailVisible"
      :columns="detailColumns"
      :static-data="detailData"
      @close="detailVisible=false"
      width="976px"
    />
  </div>
</template>

<script>
import DetailModal from '@/views/business/ysqjcdp/components/modal/detail-modal.vue'
import SwitchTab from '@/views/business/ysqjcdp/components/switch-tab.vue'
import { getBarOption, getRingOption, verticalXAXisLabel, getGradientColor } from '@/components/chart/echart-utils'
export default {
  name: 'ForecastWarning',
  components: { SwitchTab, DetailModal },
  data () {
    return {
      ybyjTabList: [
        { label: '洪水预警', value: 'hsyj' },
        { label: '预报成果', value: 'ybcg' }
      ],
      pieChartConfig: [
        { name: '蓝色预警', color: '#2CA1FF', field: 'B' },
        { name: '黄色预警', color: '#FFF600', field: 'Y' },
        { name: '橙色预警', color: '#FF9A44', field: 'O' },
        { name: '红色预警', color: '#E05736', field: 'R' }
      ],
      ybQueryDate: [this.$utils.createDate().format('YYYY-MM-DD 00:00:00'), this.$utils.createDate().format('YYYY-MM-DD 23:59:59')],
      yjQueryType: '1',
      ybyjTab: 'hsyj',
      pieOptions: null,
      chartData: [],
      pieChartData: {},
      lineOptions: null,
      achievementColumns: [
        {
          title: '站码',
          field: 'stcd',
          width: 80
        },
        {
          title: '站名',
          field: 'stnm',
          minWidth: 90
          // align: 'left'
        },
        {
          title: '预报时间',
          field: 'fymdh',
          width: 150
        },
        {
          title: '洪峰流量',
          field: 'maxq',
          width: 80,
          slots: {
            header: () => {
              return [
                <div class="d-flex-c ai-c">
                  <span>洪峰流量</span>
                  <span>(m³/s)</span>
                </div>
              ]
            }
          }
        },
        {
          title: '峰现时间',
          field: 'maxqtm',
          width: 150
        }
        // {
        //   title: '发布时间',
        //   field: 'iymdh',
        //   width: 130
        // }
      ],
      achievementTableData: [],
      tableLoading: false,
      chartLoading: false,
      detailVisible: false,
      detailColumns: [
        { title: '测站名称', field: 'stnm', minWidth: 100 },
        { title: '站码', field: 'stcd', width: 80 },
        { title: '站类', field: 'sttpName', width: 100 },
        {
          title: '预警等级',
          field: 'warnLevelName',
          minWidth: 100
        },
        {
          title: '预警类别',
          field: 'warnType',
          width: 100,
          slots: {
            default: ({ row }) => {
              return [
                <div>{row.warnType === 'Z' ? '水位' : '流量'}</div>
              ]
            }
          }
        },
        { title: '水位', field: 'z', width: 80 },
        { title: '流量', field: 'q', width: 80 },
        { title: '预警时间', field: 'startTime', width: 160 }
      ],
      detailData: []
    }
  },
  computed: {
    pieTotal () {
      const total = this.pieChartConfig.reduce((pre, cur) => {
        return pre + (this.pieChartData[cur.field] ?? 0)
      }, 0)
      return total
    },
    queryTabList () {
      return [
        {
          label: '今日以来',
          value: '1'
        },
        {
          label: new Date().getHours() + '时以来',
          value: '2'
        },
        {
          label: '1h',
          value: '3'
        },
        {
          label: '3h',
          value: '4'
        },
        {
          label: '6h',
          value: '5'
        },
        {
          label: '12h',
          value: '6'
        },
        {
          label: '24h',
          value: '7'
        }
      ]
    },
    warnLevelMap () {
      return this.pieChartConfig.reduce((pre, cur) => {
        pre[cur.field] = cur.name
        return pre
      }, {})
    }
  },
  watch: {
    ybyjTab: {
      immediate: true,
      handler (val) {
        if (val === 'hsyj') {
          this.fetchChartData()
        } else {
          this.fetchTableData()
        }
      }
    }
  },
  methods: {
    setPieOptions () {
      this.pieChartData = {
        B: this.chartData.filter(item => item.warnLevel === 'B').length,
        Y: this.chartData.filter(item => item.warnLevel === 'Y').length,
        O: this.chartData.filter(item => item.warnLevel === 'O').length,
        R: this.chartData.filter(item => item.warnLevel === 'R').length
      }
      const result = getRingOption({
        color: this.pieChartConfig.map(item => item.color),
        data: this.pieChartConfig.map(item => {
          return {
            name: item.name,
            value: this.pieChartData[item.field] ?? 0
          }
        })
      })
      result.series[0].radius = ['94%', '93%']
      result.series[1].radius = ['91%', '90%']
      result.series[2].radius = ['78%', '82%']
      this.pieOptions = result
    },
    setLineOptions () {
      const group = this.chartData.reduce((pre, cur) => {
        (pre[cur.addvnm] = pre[cur.addvnm] || []).push(cur)
        return pre
      }, {})
      const data = []
      Object.entries(group).forEach(([key, value]) => {
        data.push({
          name: key,
          b: value.filter(item => item.warnLevel === 'B').length,
          y: value.filter(item => item.warnLevel === 'Y').length,
          r: value.filter(item => item.warnLevel === 'R').length,
          o: value.filter(item => item.warnLevel === 'O').length
        })
      })
      const result = getBarOption({
        yAxisName: '个',
        xAxis: data.map(r => r.name),
        isArea: true,
        series: [
          {
            name: '蓝色预警',
            type: 'line',
            color: '#2CA1FF',
            data: data.map(r => {
              return {
                ...r,
                value: r.b
              }
            })
          },
          {
            name: '黄色预警',
            type: 'line',
            color: '#FFF600',
            data: data.map(r => {
              return {
                ...r,
                value: r.y
              }
            })
          },
          {
            name: '橙色预警',
            type: 'line',
            color: '#FFAC52',
            data: data.map(r => {
              return {
                ...r,
                value: r.o
              }
            })
          },
          {
            name: '红色预警',
            type: 'line',
            color: '#FF3000',
            data: data.map(r => {
              return {
                ...r,
                value: r.r
              }
            })
          }
        ]
      })
      if (!data.length) {
        result.grid.left = 20
      } else {
        result.grid.left = 30
      }
      result.grid.bottom = -6
      result.grid.right = 0
      result.grid.top = 30
      result.xAxis = {
        ...result.xAxis,
        axisLabel: {
          show: true,
          interval: 0,
          formatter: verticalXAXisLabel,
          color: '#FFFFFF'
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: 'rgba(233,237,240,0.1)'
          }
        }
      }
      result.yAxis.axisLabel.color = '#FFFFFF'
      result.yAxis.splitLine.show = false
      result.yAxis.axisLine = {
        show: true,
        lineStyle: {
          color: 'rgba(233,237,240,0.1)'
        }
      }
      result.yAxis.nameTextStyle = {
        color: '#FFFFFF',
        fontSize: '12px',
        padding: [0, 0, 0, -20]
      }
      result.series.forEach(item => {
        item.areaStyle = {
          color: item.color ? getGradientColor(item.color + '99', '#044ea600') : null
        }
      })
      result.tooltip.appendToBody = true
      this.lineOptions = result
    },
    async fetchChartData () {
      this.chartLoading = true
      const timeList = this.getHistoryTime()
      const data = await this.$request.formDataPost(window.outApiJs + '/app/warn/warnbdata/listPage',
        {

          startTime: timeList[0], // 预警开始时间
          endTime: timeList[1] // 预警结束时间
        }, false, 'POST', true)
      this.chartData = data.list ?? []
      this.setPieOptions()
      this.setLineOptions()
      this.chartLoading = false
    },
    async fetchTableData () {
      this.tableLoading = true
      // console.log({ ybQueryDate: this.ybQueryDate })
      // const timeList = this.getFutureTime()
      const data = await this.$request.formDataPost(window.outApiJs + '/app/forecast/result/overview/page',
        {
          // st: '2023-08-12 00:00:00',
          // et: '2023-09-14 00:00:00',
          st: this.ybQueryDate[0],
          et: this.ybQueryDate[1],
          stcdnm: '',
          page: '1',
          limit: '1000'// 暂写死
        }, false, 'POST', true)
      this.achievementTableData = data.list ?? []
      this.tableLoading = false
    },
    // getFutureTime (day = this.ybQueryType) {
    //   const today = this.$utils.createDate()
    //   const futureDay = today.add(Number(day), 'day')
    //   const st = futureDay.startOf('day').format('YYYY-MM-DD HH:mm:ss')
    //   const et = futureDay.endOf('day').format('YYYY-MM-DD HH:mm:ss')
    //   return [st, et]
    // },
    getHistoryTime (type = this.yjQueryType) {
      const today = this.$utils.createDate()
      const todayStr = today.format('YYYY-MM-DD HH:mm:ss')
      switch (type) {
        case '1':// 今日以来
          return [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), todayStr]
        case '2': // 整点以来
          return [today.format('YYYY-MM-DD HH') + ':00:00', todayStr]
        case '3': // 1h
          return [today.subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss'), todayStr]
        case '4': // 3h
          return [today.subtract(3, 'hour').format('YYYY-MM-DD HH:mm:ss'), todayStr]
        case '5': // 6h
          return [today.subtract(6, 'hour').format('YYYY-MM-DD HH:mm:ss'), todayStr]
        case '6': // 12h
          return [today.subtract(12, 'hour').format('YYYY-MM-DD HH:mm:ss'), todayStr]
        case '7': // 24h
          return [today.subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'), todayStr]
      }
    },
    showReverseCheck (field) {
      this.detailVisible = true
      this.detailData = this.chartData.filter(item => {
        item.warnType === 'Z' ? item.z = item.maxValue : item.q = item.maxValue
        return item.warnLevel === field
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.blue-select.blue-date-picker {
  width: 250px !important;
}

.pie-legend {
  .color-rect {
    position: relative;
    background-color: currentcolor;
    width: 10px;
    height: 10px;
    margin-right: 7px;

    // &::before {
    //   content: "";
    //   background-color: currentcolor;
    //   position: absolute;
    //   top: 6px;
    //   left: -20px;
    //   width: 10px;
    //   height: 10px;
    // }
  }
}

.chart-total {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
